package com.xunyin.modules.mtorder.service.impl;


import com.github.pagehelper.util.StringUtil;
import com.xunyin.api.XunyinException;
import com.xunyin.common.dto.OrderUserDto;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.enums.OrderStatusEnumV;
import com.xunyin.enums.OrderTypeEnum;
import com.xunyin.enums.PayStatusEnum;
import com.xunyin.modules.mtorder.domain.MtOrder;
import com.xunyin.modules.mtorder.service.TOrderServiceOld;
import com.xunyin.modules.mtorder.service.dto.OrderDto;
import com.xunyin.modules.mtorder.service.mapper.MtOrderMapper;
import com.xunyin.modules.user.domain.SysXbuser;
import com.xunyin.modules.user.service.SysXbuserService;
import com.xunyin.modules.user.service.dto.UserOrderDto;
import com.xunyin.utils.CommonUtilV;
import com.xunyin.utils.DateUtilV;
import com.xunyin.utils.SeqUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 订单接口实现类
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Service
@RequiredArgsConstructor
@Slf4j
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TOrderServiceOldImpl extends BaseServiceImpl<MtOrderMapper, MtOrder> implements TOrderServiceOld {

    @Autowired
    private MtOrderMapper mtOrderMapper;

    @Autowired
    private SysXbuserService sysXbuserService;

    @Override
    public MtOrder saveOrder(OrderDto orderDto) {
        MtOrder mtOrder;
        if (null != orderDto.getId() && orderDto.getId() > 0) {
            mtOrder = mtOrderMapper.selectById(orderDto.getId());
        } else {
            mtOrder = new MtOrder();
        }
        String orderSn;
        if (orderDto.getId() == null || orderDto.getId() < 1) {
            orderSn = CommonUtilV.createOrderSN(orderDto.getUserId() + "");
            mtOrder.setOrderSn(orderSn);
        } else {
            orderSn = mtOrder.getOrderSn();
        }

        mtOrder.setUserId(orderDto.getUserId());
        mtOrder.setStoreId(orderDto.getStoreId());
        mtOrder.setCouponId(orderDto.getCouponId());
        mtOrder.setParam(orderDto.getParam());
        mtOrder.setRemark(orderDto.getRemark());
        mtOrder.setStatus(OrderStatusEnumV.CREATED.getKey());
        mtOrder.setType(orderDto.getType());
        mtOrder.setAmount(orderDto.getAmount());
        mtOrder.setPayAmount(orderDto.getPayAmount());
        mtOrder.setDiscount(orderDto.getDiscount());
        mtOrder.setPayStatus(PayStatusEnum.WAIT.getKey());
        mtOrder.setPointAmount(orderDto.getPointAmount());
        mtOrder.setUsePoint(orderDto.getUsePoint());
        mtOrder.setOrderMode(orderDto.getOrderMode());
        mtOrder.setPayType(orderDto.getPayType());
        mtOrder.setOperator(orderDto.getOperator());
        mtOrder.setStaffId(orderDto.getStaffId());
        mtOrder.setIsVisitor(orderDto.getIsVisitor());
        mtOrder.setUpdateTime(new Date());
        if (mtOrder.getId() == null || mtOrder.getId() <= 0) {
            mtOrder.setCreateTime(new Date());
        }
        // 核销码
        if (mtOrder.getVerifyCode() == null) {
            mtOrder.setVerifyCode(SeqUtil.getRandomNumber(6));
        }

        // 首先生成订单
        mtOrderMapper.insert(mtOrder);
        MtOrder orderInfo = mtOrderMapper.selectById(mtOrder.getId());
        mtOrder.setId(orderInfo.getId());

        return orderInfo;
    }

    /**
     * 更新订单
     *
     * @param orderDto
     */
    @Override
    @Transactional
    // @OperationServiceLog(description = "更新订单信息")
    public MtOrder updateOrder(OrderDto orderDto) {
        MtOrder mtOrder = mtOrderMapper.selectById(orderDto.getId());
        if (null == mtOrder || OrderStatusEnumV.DELETED.getKey().equals(mtOrder.getStatus())) {
            //throw new BusinessCheckException("该订单状态异常");
            throw new XunyinException("该订单状态异常");
        }

        mtOrder.setId(orderDto.getId());
        mtOrder.setUpdateTime(new Date());

        if (null != orderDto.getOperator()) {
            mtOrder.setOperator(orderDto.getOperator());
        }

        if (null != orderDto.getStatus()) {
            mtOrder.setStatus(orderDto.getStatus());
            if (orderDto.getStatus().equals(OrderStatusEnumV.CANCEL.getKey()) || orderDto.getStatus().equals(OrderStatusEnumV.CREATED.getKey())) {
                orderDto.setPayStatus(PayStatusEnum.WAIT.getKey());
            }
        }

        if (null != orderDto.getPayAmount()) {
            mtOrder.setPayAmount(orderDto.getPayAmount());
        }

        if (null != orderDto.getAmount()) {
            mtOrder.setAmount(orderDto.getAmount());
        }

        if (null != orderDto.getVerifyCode() && StringUtil.isNotEmpty(orderDto.getVerifyCode())) {
            if (orderDto.getVerifyCode().equals(mtOrder.getVerifyCode())) {
                mtOrder.setStatus(OrderStatusEnumV.DELIVERED.getKey());
                mtOrder.setVerifyCode("");
            } else {
                //throw new BusinessCheckException("核销码错误，请确认！");
                throw new XunyinException("该订单状态异常");
            }
        }

        if (null != orderDto.getDiscount()) {
            mtOrder.setDiscount(orderDto.getDiscount());
        }

        if (null != orderDto.getPayTime()) {
            mtOrder.setPayTime(orderDto.getPayTime());
        }

        if (null != orderDto.getPayStatus()) {
            mtOrder.setPayStatus(orderDto.getPayStatus());
        }

/*        if (null != orderDto.getExpressInfo()) {
            mtOrder.setExpressInfo(JSONObject.toJSONString(orderDto.getExpressInfo()));
        }*/

        if (null != orderDto.getOrderMode()) {
            mtOrder.setOrderMode(orderDto.getOrderMode());
        }

        if (null != orderDto.getRemark()) {
            mtOrder.setRemark(orderDto.getRemark());
        }

        mtOrderMapper.updateById(mtOrder);
        return mtOrder;
    }

    /**
     * 根据订单号获取订单详情
     *
     * @param orderSn 订单号
     */
    @Override
    public UserOrderDto getOrderByOrderSn(String orderSn) {
        MtOrder orderInfo = mtOrderMapper.findByOrderSn(orderSn);
        if (orderInfo == null) {
            return null;
        }

        return this.getOrderDetail(orderInfo, true);
    }

    /**
     * 处理订单详情
     *
     * @param orderInfo
     * @return UserOrderDto
     */
    private UserOrderDto getOrderDetail(MtOrder orderInfo, boolean needAddress) {
        UserOrderDto dto = new UserOrderDto();

        dto.setId(orderInfo.getId());
        dto.setUserId(orderInfo.getUserId());
        dto.setCouponId(orderInfo.getCouponId());
        dto.setOrderSn(orderInfo.getOrderSn());
        dto.setRemark(orderInfo.getRemark());
        dto.setType(orderInfo.getType());
        dto.setPayType(orderInfo.getPayType());
        dto.setOrderMode(orderInfo.getOrderMode());
        dto.setCreateTime(DateUtilV.formatDate(orderInfo.getCreateTime(), "yyyy.MM.dd HH:mm"));
        dto.setUpdateTime(DateUtilV.formatDate(orderInfo.getUpdateTime(), "yyyy.MM.dd HH:mm"));
        dto.setAmount(orderInfo.getAmount());
        dto.setIsVisitor(orderInfo.getIsVisitor());
        dto.setStaffId(orderInfo.getStaffId());
        dto.setStoreId(orderInfo.getStoreId());
        dto.setVerifyCode("");

        // 核销码为空，说明已经核销
        if (orderInfo.getVerifyCode() == null || StringUtil.isEmpty(orderInfo.getVerifyCode())) {
            dto.setIsVerify(true);
        } else {
            dto.setIsVerify(false);
        }

        if (orderInfo.getPayAmount() != null) {
            dto.setPayAmount(orderInfo.getPayAmount());
        } else {
            dto.setPayAmount(new BigDecimal("0"));
        }

        if (orderInfo.getDiscount() != null) {
            dto.setDiscount(orderInfo.getDiscount());
        } else {
            dto.setDiscount(new BigDecimal("0"));
        }

        if (orderInfo.getPointAmount() != null) {
            dto.setPointAmount(orderInfo.getPointAmount());
        } else {
            dto.setPointAmount(new BigDecimal("0"));
        }

        dto.setStatus(orderInfo.getStatus());
        dto.setParam(orderInfo.getParam());
        dto.setPayStatus(orderInfo.getPayStatus());

        if (orderInfo.getUsePoint() != null) {
            dto.setUsePoint(orderInfo.getUsePoint());
        } else {
            dto.setUsePoint(0);
        }
        if (orderInfo.getPayTime() != null) {
            dto.setPayTime(DateUtilV.formatDate(orderInfo.getPayTime(), "yyyy.MM.dd HH:mm"));
        }

        if (dto.getType().equals(OrderTypeEnum.PRESTORE.getKey())) {
            dto.setTypeName(OrderTypeEnum.PRESTORE.getValue());
        } else if (dto.getType().equals(OrderTypeEnum.PAYMENT.getKey())) {
            dto.setTypeName(OrderTypeEnum.PAYMENT.getValue());
        } else if (dto.getType().equals(OrderTypeEnum.GOOGS.getKey())) {
            dto.setTypeName(OrderTypeEnum.GOOGS.getValue());
        } else if (dto.getType().equals(OrderTypeEnum.MEMBER.getKey())) {
            dto.setTypeName(OrderTypeEnum.MEMBER.getValue());
        } else if (dto.getType().equals(OrderTypeEnum.RECHARGE.getKey())) {
            dto.setTypeName(OrderTypeEnum.RECHARGE.getValue());
        }

        if (dto.getStatus().equals(OrderStatusEnumV.CREATED.getKey())) {
            dto.setStatusText(OrderStatusEnumV.CREATED.getValue());
        } else if (dto.getStatus().equals(OrderStatusEnumV.CANCEL.getKey())) {
            dto.setStatusText(OrderStatusEnumV.CANCEL.getValue());
        } else if (dto.getStatus().equals(OrderStatusEnumV.PAID.getKey())) {
            dto.setStatusText(OrderStatusEnumV.PAID.getValue());
        } else if (dto.getStatus().equals(OrderStatusEnumV.DELIVERY.getKey())) {
            dto.setStatusText(OrderStatusEnumV.DELIVERY.getValue());
        } else if (dto.getStatus().equals(OrderStatusEnumV.DELIVERED.getKey())) {
            dto.setStatusText(OrderStatusEnumV.DELIVERED.getValue());
        } else if (dto.getStatus().equals(OrderStatusEnumV.RECEIVED.getKey())) {
            dto.setStatusText(OrderStatusEnumV.RECEIVED.getValue());
        } else if (dto.getStatus().equals(OrderStatusEnumV.DELETED.getKey())) {
            dto.setStatusText(OrderStatusEnumV.DELETED.getValue());
        }

        // 订单所属店铺
/*        MtStore storeInfo = storeService.queryStoreById(orderInfo.getStoreId());
        dto.setStoreInfo(storeInfo);*/

        // 下单用户信息直接取会员个人信息
        OrderUserDto userInfo = new OrderUserDto();
        //MtUser user = memberService.queryMemberById(orderInfo.getUserId());
        SysXbuser user = sysXbuserService.getById(orderInfo.getUserId());
        if (user != null) {
            userInfo.setId(user.getId());
            userInfo.setName(user.getUserName());
            userInfo.setMobile(user.getUserAccount());
            //userInfo.setCardNo(user.getCarNo());
            //userInfo.setAddress(user.getAddress());
            dto.setUserInfo(userInfo);
        }

        return dto;
    }

    @Override
    @Transactional
    //@OperationServiceLog(description = "修改订单为已支付")
    public boolean setOrderPayed(Integer orderId) {
        MtOrder mtOrder = mtOrderMapper.selectById(orderId);

        if (mtOrder == null) {
            return false;
        }

        if (mtOrder.getPayStatus().equals(PayStatusEnum.SUCCESS.getKey())) {
            return true;
        }

        //UserOrderDto orderInfo = this.getOrderDetail(tOrder, false);

        OrderDto reqDto = new OrderDto();
        reqDto.setId(orderId);
        reqDto.setStatus(OrderStatusEnumV.PAID.getKey());
        reqDto.setPayStatus(PayStatusEnum.SUCCESS.getKey());
        reqDto.setPayTime(new Date());
        reqDto.setUpdateTime(new Date());
        this.updateOrder(reqDto);

        return true;
    }
}
